Skip to content

[Cherry-Pick][Operator Mechanism]Add K-dim consistency check to matmul_grad InferMeta - #79839

Merged
sneaxiy merged 4 commits into
PaddlePaddle:release/3.4from
feixi139:cp79800_release34
Oct 15, 2026
Merged

sneaxiy merged 4 commits into
PaddlePaddle:release/3.4from
feixi139:cp79800_release34

Conversation

@feixi139

@feixi139 feixi139 commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

PR Category

Operator Mechanism

PR Types

Bug fixes

Description

本 PR 修复 matmul_grad 反向算子不校验收缩维(K 维)一致性导致的前后向契约不一致问题。前向 matmul 在 MatmulInferMeta 中会强制要求 X、Y 的收缩维相等,但反向 matmul_grad 复用了通用的 GeneralBinaryGradInferMeta,只把 X、Y 的 meta 原样共享给 dx、dy,跳过了这道校验,于是前向会拦截的 K 维不匹配输入,反向却照单全收。核心问题和结果可以概括为:

  1. 前向校验、反向不校验:GeneralBinaryGradInferMeta 只做 dx->share_meta(x)、dy->share_meta(y),没有任何形状约束。前向被 PADDLE_ENFORCE_EQ(K_lhs, K_rhs) 拒绝的 K 维不匹配组合,直接单独调用私有反向算子 paddle._C_ops.matmul_grad 时不会报错。
  2. 新增专用 InferMeta:新增设备无关的 MatmulGradInferMeta,复刻前向的收缩维一致性检查,同时保留原有的 share_meta 行为。
  3. 覆盖全部 dense 反向路由:matmul_grad 在动态图、PIR 静态图、legacy 静态图三套 yaml 中各有定义,另有同根因的 legacy_matmul_grad(前向 legacy_matmul 同样走 MatmulInferMeta)。四条 dense 路径全部改为路由到 MatmulGradInferMeta;稀疏 matmul_grad 无转置参数、属独立算子族,保持不动。

1. matmul_grad 缺失 K 维一致性校验

问题

前向 MatmulInferMeta(paddle/phi/infermeta/binary.cc)按 transpose_x/transpose_y 定位 X、Y 的收缩维并强制相等:

const int64_t K_lhs = dims_x[lhs_reduce_dim];
const int64_t K_rhs = dims_y[rhs_reduce_dim];
if (config.is_runtime || (K_rhs != -1 && K_lhs != -1)) {
  PADDLE_ENFORCE_EQ(K_lhs, K_rhs, ...);
}

反向 matmul_grad 的 infer_meta 却指向通用的 GeneralBinaryGradInferMeta(paddle/phi/infermeta/backward.cc):

void GeneralBinaryGradInferMeta(const MetaTensor& x, const MetaTensor& y,
                                MetaTensor* dx, MetaTensor* dy) {
  if (dx) dx->share_meta(x);
  if (dy) dy->share_meta(y);
}

它只抄形状、不校验收缩维,于是前向会拦的 K 维不匹配输入,反向不拦:

import paddle
# 前向 matmul([1024,0], [4096,64]):X 末维 0 != Y 首维 4096 -> 前向抛 InvalidArgument
# 反向直接单调:不报错,照样返回 dx=[1024,0]、dy=[4096,64]
paddle._C_ops.matmul_grad(
    paddle.empty([1024, 0]), paddle.empty([4096, 64]),
    paddle.empty([1024, 64]), False, False)

torch 对复原出的前向组合同样一律 RuntimeError: mat1 and mat2 shapes cannot be multiplied。这是 Paddle 自身前后向契约不一致:前向校验 K 维,反向 InferMeta 漏了这道校验。

说明:matmul_grad 是私有反向算子,正常训练中它只会拿到已被前向校验过的合法 shape,K 维不匹配不会自然出现;这些用例是测试直接单独调用反向算子构造的合成输入。本 PR 的价值在于"前后向契约一致"与对齐 torch,而非修复实际训练路径的 bug。

改动
  • 在 paddle/phi/infermeta/backward.cc 新增设备无关的 MatmulGradInferMeta,复刻前向的收缩维定位与一致性检查,并保留原有 share_meta:
void MatmulGradInferMeta(const MetaTensor& x, const MetaTensor& y,
                         bool transpose_x, bool transpose_y,
                         MetaTensor* dx, MetaTensor* dy, MetaConfig config) {
  std::vector<int64_t> dims_x = common::vectorize(x.dims());
  std::vector<int64_t> dims_y = common::vectorize(y.dims());
  const auto ndims_x = dims_x.size();
  const auto ndims_y = dims_y.size();
  if (ndims_x > 0 && ndims_y > 0) {
    const int64_t lhs_reduce_dim = (ndims_x == 1) ? 0 : ndims_x - 1 - transpose_x;
    const int64_t rhs_reduce_dim = (ndims_y == 1) ? 0 : ndims_y - 2 + transpose_y;
    const int64_t K_lhs = dims_x[lhs_reduce_dim];
    const int64_t K_rhs = dims_y[rhs_reduce_dim];
    if (config.is_runtime || (K_rhs != -1 && K_lhs != -1)) {
      PADDLE_ENFORCE_EQ(K_lhs, K_rhs, common::errors::InvalidArgument(...));
    }
  }
  if (dx) dx->share_meta(x);
  if (dy) dy->share_meta(y);
}
  • 在 paddle/phi/infermeta/backward.h 补充对应声明(末尾 MetaConfig config = MetaConfig(),由代码生成自动追加)。
  • 采用 ndims_x > 0 && ndims_y > 0 的守卫,避免对空维索引越界;config.is_runtime 与 -1 判断与前向保持一致,兼容静态图未知维。
  • 收缩维一致性检查天然允许 K 维为 0 的合法零尺寸反向(如 [M,0]·[0,N]),仅拒绝 K 维不匹配。
修改后结果
  • 直接调用 matmul_grad 时,K 维不匹配输入在进入 kernel 前明确抛出 InvalidArgument,与前向 matmul 及 torch 一致;
  • 校验点在设备无关的 InferMeta,一处覆盖 CPU / GPU / oneDNN / XPU 全部后端,静态图编译期即可拦截;
  • 合法(K 一致,含 K=0)的反向计算行为不变。

2. 覆盖全部 dense 反向路由

问题

matmul_grad 的 infer_meta 路由分散在多套 yaml 中,若只改其中一处,其余执行模式仍不拦:

  • paddle/phi/ops/yaml/inconsistent/dygraph_backward.yaml(动态图)
  • paddle/phi/ops/yaml/inconsistent/static_backward.yaml(PIR 静态图)
  • paddle/phi/ops/yaml/legacy/static_backward.yaml(legacy 静态图)

此外 paddle/phi/ops/yaml/inconsistent/static_backward.yaml 中的 legacy_matmul_grad 属同一根因——其前向 legacy_matmul 同样走 MatmulInferMeta 校验 K 维,反向也用 GeneralBinaryGradInferMeta。

改动
  • 将上述 3 处 matmul_grad 与 1 处 legacy_matmul_grad 的 infer_meta 由 GeneralBinaryGradInferMeta / param : [x, y] 改为 MatmulGradInferMeta / param : [x, y, transpose_x, transpose_y];
  • legacy_matmul_grad 多一个 alpha 参数,但 K 维校验与 alpha 无关,复用同一 MatmulGradInferMeta(alpha 不参与 infer_meta);
  • 稀疏 matmul_grad(paddle/phi/ops/yaml/sparse_backward.yaml)无 transpose_x/transpose_y 参数、走稀疏 kernel、属独立算子族,且本次问题场景均为 dense,保持不动。
修改后结果
  • 动态图、PIR 静态图、legacy 静态图以及 legacy_matmul 的全部 dense 反向路径统一获得 K 维校验;
  • 稀疏路径行为不变。

修改后的总体行为

类别 之前 之后
matmul_grad K 维不匹配(直调反向) 不报错,返回 dx/dy 抛 InvalidArgument,对齐前向与 torch
legacy_matmul_grad K 维不匹配 不报错 抛 InvalidArgument
K 维一致(含 K=0 的合法零尺寸反向) 正常返回 正常返回(不变)
稀疏 matmul_grad 走 GeneralBinaryGradInferMeta 不变

合法输入的结果不变;修改只影响原本被静默接受的 K 维不匹配反向请求。

devPR:#79800

是否引起精度变化

否

matmul_grad was routed through GeneralBinaryGradInferMeta, which only
shares x/y meta with dx/dy and skips the contraction (K) dimension
check that the forward MatmulInferMeta enforces. As a result the
backward op silently accepted K-mismatched inputs that the forward
rejects (returning results instead of raising).

Add a dedicated MatmulGradInferMeta that replicates the forward K
check and keeps the original share_meta behavior, and route the dense
matmul_grad (dygraph / PIR / legacy static) and legacy_matmul_grad to
it. Sparse matmul_grad has no transpose args and is left unchanged.
The K-dim check keyed on config.is_runtime, but the backward InferMeta is
invoked with the default MetaConfig (is_runtime=true) even at graph-build
time, so it wrongly rejected legal dynamic-shape graphs with a -1 dim (e.g.
InputSpec([-1, -1])). A real runtime tensor never carries a -1 dim, so
enforcing only when both contraction dims are concrete still catches every
genuine K mismatch while allowing symbolic shapes.
@codecov-commenter

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (release/3.4@64f001f). Learn more about missing BASE report.

Additional details and impacted files
@@               Coverage Diff               @@
##             release/3.4    #79839   +/-   ##
===============================================
  Coverage               ?   100.00%           
===============================================
  Files                  ?         1           
  Lines                  ?        19           
  Branches               ?         0           
===============================================
  Hits                   ?        19           
  Misses                 ?         0           
  Partials               ?         0           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

wanghuancoder
wanghuancoder previously approved these changes Oct 10, 2026
zhangbo9674
zhangbo9674 previously approved these changes Oct 10, 2026
matmul_grad now routes its InferMeta through the new MatmulGradInferMeta,
whose signature carries a MetaConfig argument. Add it to the generator
allowlist so the PIR op build invokes it with phi::MetaConfig(false, false),
satisfying the CI requirement that infermeta funcs taking MetaConfig stay in
sync with op_build_gen.py.

@wanghuancoder wanghuancoder left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@feixi139 feixi139 closed this Oct 13, 2026
@wanghuancoder wanghuancoder reopened this Oct 13, 2026
@Paddle-Review-Bot

Paddle-Review-Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Paddle-Bot Review Board (review完成)

序号 位置 优先级 规则来源 状态
1 PIR 生成器白名单新增 MatmulGradInferMeta 为空操作,且与 devPR 不一致 P3 默认规则 🚧

Powered by Nyanpasu claude with Opus 5 默认推理级别, please check the suggestions carefully.

'CSoftmaxWithCrossEntropyGradInferMeta',
'CSoftmaxWithMultiLabelCrossEntropyGradInferMeta',
'LSTMGradInferMeta',
'MatmulGradInferMeta',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 该白名单项是空操作,且与 devPR #79800 不一致。

_INFERMETA_NEED_META_CONFIG 唯一作用是让 PIR 生成的 build / infer_meta 代码在调用末尾追加 phi::MetaConfig(false, false)(op_build_gen.py 的 CREATE_INFER_META_FUNC_WITH_META_CONFIG_TEMPLATE,op_infermeta_func_gen.py 同理)。但本 PR 新增的 MatmulGradInferMeta(paddle/phi/infermeta/backward.cc 第 732-788 行)在第三个 commit 之后已完全不读取 config——判定条件是 K_lhs != -1 && K_rhs != -1,与 config.is_runtime 无关。因此注册后只是把默认 MetaConfig()(is_runtime=true)换成 MetaConfig(false, false),不产生任何行为差异;白名单里其余条目(如 MatmulInferMeta)都是真正使用 config 的函数。

另外,devPR #79800(已于 develop 合入,a48f1c3)并不包含本行,本 cherry-pick 仅此一处与 devPR 有差异,PR 描述中也未提及该文件,会造成 release/3.4 与 develop 的生成器白名单不一致,后续 cherry-pick 易产生冲突。

建议:若无实际依赖,删掉该行以与 devPR 保持一致(同时可考虑移除 MatmulGradInferMeta 中未被使用的 MetaConfig config 形参);若确有保留必要,请在描述中补充原因并同步回 develop。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

devPR #79857 已补充合入

@feixi139

Copy link
Copy Markdown
Contributor Author

/re-run all-failed

@sneaxiy
sneaxiy merged commit 59bb13b into PaddlePaddle:release/3.4 Oct 15, 2026
344 of 377 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants